package com.wish233.model.protocol;


import com.wish233.model.protocol.enums.ProtocolMessageSerializerEnum;
import com.wish233.serializer.Serializer;
import com.wish233.serializer.factory.SerializerFactory;
import io.vertx.core.buffer.Buffer;

import java.io.IOException;

/**
 * @author WHH
 * 协议编码器
 */
public class ProtocolEncoder {

    public static Buffer encode(WishProtocol<?> wishProtocol) throws IOException {
        //先读请求头
        WishProtocol.Header header = wishProtocol.getHeader();
        Buffer buffer = Buffer.buffer();
        buffer.appendByte(header.getMagicHigh());
        buffer.appendByte(header.getMagicLow());
        buffer.appendByte(header.getVersion());
        buffer.appendByte(header.getType());
        buffer.appendByte(header.getSerializer());
        buffer.appendByte(header.getStatus());
        buffer.appendLong(header.getRequestId());
        //获得序列化器
        ProtocolMessageSerializerEnum serializerEnum = ProtocolMessageSerializerEnum.getEnumByKey(header.getSerializer());
        if (serializerEnum == null) {
            throw new RuntimeException("序列化器" + header.getSerializer() + "不存在");
        }
        Serializer serializer = SerializerFactory.getInstance(serializerEnum.getValue());
        //序列化
        byte[] bytes = serializer.serialize(wishProtocol.getBody());
        //写入长度
        buffer.appendInt(bytes.length);
        buffer.appendBytes(bytes);
        return buffer;
    }

}
